package cn.xdf.demo01;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;

public class Demo02_queryParse {
    @Test
    public void test01() throws Exception{

        //索引库目录
        FSDirectory dir=FSDirectory.open(new File("D:/aaa/index"));

        //索引库读取对象
        DirectoryReader reader= IndexReader.open(dir);

        //索引库搜索对象
        IndexSearcher indexSearcher=new IndexSearcher(reader);

        //分词器
        IKAnalyzer analyzer = new IKAnalyzer();

        //创建查询解析器
        QueryParser queryParser=new QueryParser(Version.LUCENE_4_10_3,"title",analyzer);

        //执行查询
        Query query = queryParser.parse("神舟战神");

        //结果集对象（总记录数，文档id和分值，最大分值）
        TopDocs topDocs = indexSearcher.search(query, 100);

        //保护所有的文档id和对应的分支
        ScoreDoc[] scoreDocs =topDocs.scoreDocs;

        for(ScoreDoc scoreDoc:scoreDocs){

            System.out.println("文档id:"+scoreDoc.doc);
            //根据文档id搜索出对应的文档
            Document doc=indexSearcher.doc(scoreDoc.doc);

            String id =doc.get("id");
            String name =doc.get("name");
            String title =doc.get("title");
            String price =doc.get("price");
            String pic =doc.get("pic");

            System.out.println("匹配分值："+scoreDoc.score);
            System.out.println("商品id:"+id);
            System.out.println("商品名称："+name);
            System.out.println("商品标题:"+title);
            System.out.println("商品价格:"+price);
            System.out.println("商品图片："+pic);
            System.out.println("-------------------");
        }

        reader.close();
        dir.close();
    }
}
